package com.yq.master.interceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yq.core.constant.Constant;
import com.yq.core.entity.SysLogOperationEntity;
import com.yq.core.service.SysLogOperationService;
import com.yq.core.util.IpUtil;
import com.yq.core.util.Result;
import com.yq.master.annotation.AzerothAutowired;
import com.yq.master.bean.WebUserBean;
import com.yq.master.staticdata.StaticData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.WebUtils;

/**
 * 文件名：用户权限拦截器
 * 创建人：yinquan
 * 创建日期: 2016-12-22 13:43
 * 描述：登录用户权限拦截
 * 版本号：1.0
 */
@Controller
//@RequestMapping(value = "/login")
public class PowerInterceptor extends HandlerInterceptorAdapter{

    private static final Logger logger = LoggerFactory.getLogger(PowerInterceptor.class);

    @AzerothAutowired
    public SysLogOperationService sysLogOperationService;

    @Override
    public void afterCompletion(HttpServletRequest request,	HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request,	HttpServletResponse response, Object handler) throws Exception {
        super.afterConcurrentHandlingStarted(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request,HttpServletResponse response, Object handler,	ModelAndView modelAndView)throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @SuppressWarnings("unchecked")
    @Override
    public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {

        SysLogOperationEntity sysLogOperationEntity = new SysLogOperationEntity();
        String url = request.getRequestURI();
        String m = request.getParameter("_m");
        Date date = new Date();

        // 设置基本信息
        WebUserBean webUserBean = getWebUserBean(request);
        if(webUserBean!=null) {
            sysLogOperationEntity.setUserUid(webUserBean.getUid());
            sysLogOperationEntity.setAccount(webUserBean.getAccount());
            sysLogOperationEntity.setRealName(webUserBean.getNickname());
            sysLogOperationEntity.setName(webUserBean.getName());
            sysLogOperationEntity.setIp(IpUtil.getIpAddr(request));
            sysLogOperationEntity.setCreateAt(date);
            sysLogOperationEntity.setCreateBy("system");
        }

        Map<String, Object> power = null;

        if(m.equals("init")) {
            // 页面初始化
            power = (Map<String, Object>) StaticData.MENU_POWER_URL.get(url + "?_m=" + m);
            if(power == null) {
                power = (Map<String, Object>) StaticData.MENU_POWER_URL.get(url);
            }

        } else {
            power = (Map<String, Object>) StaticData.MENU_POWER_URL.get(url);
        }

        if(power == null) {
            String requestType = request.getHeader("X-Requested-With");//ajax
            String accept = request.getHeader("accept");//

            response.setContentType("text/html; charset=utf-8" );
            request.setAttribute("code", Constant.CODE_200);
            request.setAttribute("url", url);

            if("XMLHttpRequest".equals(requestType)){
                if(accept.indexOf("application/json")>-1){//返回json
                    Result json = new Result();
                    json.resoutError("资源【"+url+"】未授权");

                    PrintWriter pw=response.getWriter();
                    //pw.write(json);
                    pw.write(JSONObject.toJSONString(json));
                    pw.flush();
                    pw.close();

                } else{
                    // ajax访问时，权限拦截
                    request.getRequestDispatcher("/error/powererror.jsp").forward(request,response);
                }
            }else{
                // 正常访问时，权限拦截
                request.getRequestDispatcher("/error/powererror.jsp").forward(request,response);
            }

            return false;
        }

        sysLogOperationEntity.setSign(m);
        sysLogOperationEntity.setUrl(power.get("url").toString());

        sysLogOperationEntity.setPowerUid(power.get("uid").toString());
        sysLogOperationEntity.setRootUid(power.get("rootUid").toString());
        sysLogOperationEntity.setBranchUid(power.get("branchUid").toString());
        sysLogOperationEntity.setLeafUid(power.get("leafUid")==null?null:power.get("leafUid").toString());
        sysLogOperationEntity.setFunType(power.get("funType").toString());

        sysLogOperationEntity.setParameter(JSONObject.toJSON(request.getParameterMap()).toString());
        sysLogOperationEntity.setHeader(JSONObject.toJSON(request.getHeaderNames()).toString());

        sysLogOperationService.insert(sysLogOperationEntity);

        return super.preHandle(request, response, handler);
    }

    // 获取session中的用户信息
    private WebUserBean getWebUserBean(ServletRequest request) {
        HttpSession session = ((HttpServletRequest) request).getSession(false);
        return (session != null ? (WebUserBean) session.getAttribute(Constant.SESSION_KEY) : null);
    }

}
